<?php
/**
 * 后台用控制器模板
 */
namespace app\admin\controller\maintain;

use app\admin\controller\AuthController;
use app\common\model as M;
use service\JsonService;

class Recomand extends AuthController
{
	public $model = '\app\common\model\Recomand';

    use \traits\ShotcutControllerTrait;
	
	/**
	 * 保存
	 */
	public function saveRoutesRels()
	{
		$post = input();
		$recomand_id = $post['recomand_id'] ?? 0;
		$rels = $post['rels'] ?? [];
		
		if ( !$recomand_id ) return JsonService::fail('推荐ID不能为空');
		
		M\RelRecomandRoutes::startTrans();
		try {
			## 先清空推荐ID下所有旧线路
			$res = M\RelRecomandRoutes::where('recomand_id',$recomand_id)->delete();
			if ( $res === false ) throw new \Exception('Error:1001');
			
			## 重新关联最新的推荐线路
			$routes = [];
			foreach ( $rels as $rel ) {
				$routes[] = [
					'recomand_id' => $recomand_id,
					'route_id'    => $rel['id'],
					'sort'        => $rel['sort'],
				];
			}
			if ( !empty($routes) ) {
				$res = (new M\RelRecomandRoutes)->saveAll($routes);
				if ( $res === false ) throw new \Exception('Error:1002');
			}
			
			M\RelRecomandRoutes::commitTrans();
			return JsonService::successful();
		} catch ( \Exception $e ) {
			M\RelRecomandRoutes::rollbackTrans();
			return JsonService::fail($e->getMessage());
		}
		M\RelRecomandRoutes::rollbackTrans();
		return JsonService::fail('操作失败');
	}
}// class end
